package com.duan.laugh.common.security.config;

import com.duan.laugh.common.security.constants.SecurityConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign配置
 * 使用FeignClient进行服务间调用，传递headers信息
 *
 * @author duanjw
 */
@Slf4j
@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            // 如果请求头没有token，从url取出access_token
            if (request.getHeader(SecurityConstants.AUTHORIZATION) == null) {
                //添加token
                requestTemplate.header(SecurityConstants.AUTHORIZATION, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, request.getParameter(SecurityConstants.ACCESS_TOKEN)));
            }
        }
    }
}
